package hero.niosocket;

import java.nio.charset.Charset;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.nio.ByteBuffer;

public class SocketReader {

    public static void main(String[] args) throws Exception {
        ByteBuffer buf = ByteBuffer.allocateDirect(1024*1024);
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(true);
        channel.connect(new InetSocketAddress("www.baidu.com", 80));
        String request = "GET " + "/ HTTP/1.1\r\n" + "User-Agent: HTTPGrab\r\n"
            + "Accept: text/*\r\n" + "Connection: close\r\n" + "Host: " 
            + "127.0.0.1" + "\r\n" + "\r\n";

        ByteBuffer header = ByteBuffer.wrap(request.getBytes("US-ASCII"));
        channel.write(header);

        int num = channel.read(buf);
        if (num == -1) {
            System.out.println("-1");
        } else {
            buf.flip();
            Charset charset = Charset.forName("UTF-8");
            System.out.println(charset.decode(buf));
        }
        channel.close();
        
    }

}
